require "Common/define"
require "Logic/Config"
require "Common/functions"

UIEquipList = {}
HelperFunc.SetUIEnv(UIEquipList)
local this = UIEquipList;

this.LuaBehaviour = nil;
this.transform = nil;

this.btn_Close = nil;
this.objEquipedItem = nil;
this.txt_Strength = nil;
this.controller = nil;
---@type GList
this.List_Equipment = nil;
this.tipController = nil;
this.tipText = nil;
this.btn_sure = nil;
this.btn_cancel = nil;

this.hasInit = false;

this.curEquipData = nil;
this.curHeroName = nil;
this.currentPartnerId = 0;
this.curHeroType = 1;
this.heroId = nil;
this.tablelist = {};
this.table_equipItem = {}
this.nothingController = nil;
this.contype=nil;
this.tipItem1 = nil
this.tipItem2 = nil
this.tipIcon1 = nil
this.tipIcon2 = nil
this.curHeroData = nil

--当前玩家信息，当前玩家配置，当前装备信息
function this.Init(herodata, equipdata)
    --区分英雄数据
    if herodata then
        this.currentPartnerId = herodata["partnerId"]
        this.curHeroName = herodata["name"];
        this.curHeroType = herodata["type"];
        this.heroId = herodata["partnerModelId"]
        this.curHeroData = herodata
    end

    if equipdata["itemId"] == nil then
        this.curEquipData = {}
        this.curEquipData.ctrollerIndex = 0
        this.curEquipData.part = equipdata["part"]
    else
        this.curEquipData = equipdata;
        this.curEquipData.ctrollerIndex = 1
    end

    local name, packageName = getUIName(PanelResNames.UIEquipList);
    panelMgr:ShowUI(name, packageName, this.onCreate, Config.useLocalUI);
end

function this.onCreate(obj)
    if not this.hasInit then
        this.hasInit = true;
        this.bgClose = obj:GetChild("bgClose");
        this.btn_Close = obj:GetChild("bgclose");
        this.List_Equipment =obj:GetChild("List_Equipment");
        this.List_Equipment.itemRenderer = this.itemRendererEquipment
        this.objEquipedItem = obj:GetChild("equipListitem");
        this.txt_Strength = obj:GetChild("refine");
        this.objCtrl = obj:GetController("c1");
        this.tipController = obj:GetController("tips");
        this.tipText = obj:GetChild("tipText");
        this.tipItem1 = obj:GetChild("equip1")
        this.tipItem2 = obj:GetChild("equip2")
        this.tipIcon1 = obj:GetChild("equip1hero"):GetChild("HeadIcon")
        this.tipIcon2 = obj:GetChild("equip2hero"):GetChild("HeadIcon")
        this.btn_sure = obj:GetChild("btn_sure");
        this.btn_cancel = obj:GetChild("btn_cancel");
        this.nothingController = obj:GetController("nothing");
        this.Txt_NoEquip = obj:GetChild("Combo_Nothing")
        this.Txt_NothingTitle = obj:GetChild("Combo_Nothing"):GetChild("title")
        this.fragmentEffectWrap = obj:GetChild("effect_zwxq").wrapTarget
        this.contype=obj:GetController("type");

        this.btn_Close.onClick:Add( this.onClickClose)
        this.bgClose.onClick:Add( this.onClickClose)
        this.btn_cancel.onClick:Add( this.onClickCancel)
    end
    this.showCurEquipInfo();
    this.initEquipList();
end

function this.OnEnable()
    ListenEvent(Config.EventType.Fresh_Equip, this.updateEquip)
    ListenEvent(Config.EventType.Fragment_Wear,this.FramRefresh)
    ListenEvent(Config.EventType.Fragment_Replace,this.FramRefresh)
end
function this.OnDisable()
    CloseEvent(Config.EventType.Fresh_Equip,this.updateEquip)
    CloseEvent(Config.EventType.Fragment_Wear,this.FramRefresh)
    CloseEvent(Config.EventType.Fragment_Replace,this.FramRefresh)
end
function this.OnDestroy()
    this.btn_Close.onClick:Clear()
    this.bgClose.onClick:Clear()
    this.btn_sure.onClick:Clear()
    this.btn_cancel.onClick:Clear()
    this.hasInit = false
end

function this.onClickClose()
    closeUI(PanelNames.UIEquipList)
end

function this.FramRefresh()
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.EquipListItem)
    if ctrlItem then
        ctrlItem.initData(this.objEquipedItem,StrangeFragmentManager.GetCurrentEquipFragment(this.currentPartnerId))
    end
    this.objCtrl.selectedIndex = 1
    local _equipTypeController = this.objEquipedItem:GetController("equipType")
    _equipTypeController.selectedIndex = 1
    this.updateEquip()
end

function this.showCurEquipInfo()
    this.objCtrl.selectedIndex = this.curEquipData.ctrollerIndex
    if this.curEquipData.ctrollerIndex == 1 then
        local _equipTypeIndex = 0
        local _equipTypeController = this.objEquipedItem:GetController("equipType")

        if this.curEquipData.part == EnumConst.EquipPartEnum.FRAGMENT then
            --如果是奇异碎片
            _equipTypeIndex = 1
            local _gemDescription = ""
            if this.curEquipData.itemId then
                local _itemModelId = this.curEquipData.itemModelId or this.curEquipData.itemId.itemModelId
                local _fragmentInfo = StrangeFragmentManager.GetTableByFragmentId(_itemModelId)
                if _fragmentInfo then
                    local _skillInfo =  G.dataTable["t_skill"][tostring(_fragmentInfo.f_SkillId)]
                    if _skillInfo and _skillInfo.f_Desc then
                        _gemDescription = getLanguage(_skillInfo.f_Desc)
                    end
                end
            end
            this.objEquipedItem:GetChild("Txt_Description").text = _gemDescription
            _equipTypeController.selectedIndex = _equipTypeIndex
            local ctrlItem = CtrlManager.GetCtrl(PanelNames.EquipListItem)
            if ctrlItem then
                ctrlItem.initData(this.objEquipedItem,StrangeFragmentManager.GetCurrentEquipFragment(this.currentPartnerId))
            end
        else
            _equipTypeController.selectedIndex = _equipTypeIndex
            local ctrlItem = CtrlManager.GetCtrl(PanelNames.EquipListItem)
            if ctrlItem then
                ctrlItem.initData(this.objEquipedItem, this.curEquipData)
            end
        end
    elseif this.curEquipData.ctrollerIndex == 0 then
        local _noEquipStr
        if this.curEquipData.part == EnumConst.EquipPartEnum.FRAGMENT then
            --还没有可以装备的奇异碎片
            _noEquipStr = getLanguage("UIEquip_HadNotGem")
        else
            --还没有可以装备的哦~~
            _noEquipStr = getLanguage("UIEquip_HasNotEquip")
        end
        this.Txt_NoEquip.text = _noEquipStr
    end
end

function this.initEquipList()
    for _, v in pairs(this.table_equipItem) do
        v.onClick:Clear();
    end

    --装备分类排序
    this.tablelist = {}
    if this.curEquipData.part == EnumConst.EquipPartEnum.FRAGMENT then
        this.tablelist = StrangeFragmentManager.GetWeaponFragmentList(this.currentPartnerId)
        this.contype.selectedIndex=1;

    else
        this.contype.selectedIndex=0;
        local _equipList = EquipManager.getEquipbyPart(this.curEquipData.part, this.currentPartnerId)
        for _, equipInfo in ipairs(_equipList) do
            -- 职业匹配 或者 奇异碎片
            if equipInfo.heroType == this.curHeroType then
                if equipInfo.partnerId then
                    local _heroData = HeroManager.getHeroDatabyPartnerId(equipInfo["partnerId"],true)
                    equipInfo.heroName = _heroData.name
                    equipInfo.heroIcon = "ui://ICONAtlas/".._heroData.icon
                end
                table.insert(this.tablelist, equipInfo)
            end
        end
        if this.tablelist and #this.tablelist > 1 then
            table.sort(this.tablelist, this.sortCondition)
        end
    end

    this.table_equipItem = {}
    this.List_Equipment:SetVirtual()
    this.List_Equipment.numItems = #this.tablelist

    --装备列表是否为空
    local _nothingControllerIndex
    local _nothingTitle
    if #this.tablelist > 0 then
        _nothingControllerIndex = 0
        _nothingTitle =  ""
    else
        _nothingControllerIndex = 1
        if this.curEquipData.part == EnumConst.EquipPartEnum.FRAGMENT then
            --参与永劫之境可获得奇异碎片
            _nothingTitle = getLanguage("UIEquip_GetGemTip")
        else
            --参与永劫之境可获得海量装备
            _nothingTitle = getLanguage("UIEquip_GetEquipTip")
        end
    end
    this.Txt_NothingTitle.text = _nothingTitle
    this.nothingController.selectedIndex = _nothingControllerIndex
end

function this.itemRendererEquipment(index,go)
    local equipData = this.tablelist[index +1]
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.EquipListItem)
    ctrlItem.initData(go, equipData, LuaBehaviour)

    local _equipTypeIndex = 0
    if this.curEquipData.part == EnumConst.EquipPartEnum.FRAGMENT then
        _equipTypeIndex = 1
    end
    go:GetController("equipType").selectedIndex = _equipTypeIndex

    local btn_replace = go:GetChild("btn_replace");
    local btn_unreplace = go:GetChild("btn_unreplace");
    btn_unreplace.onClick:Clear()
    btn_unreplace.onClick:Add( function()
        if this.curEquipData.part == EnumConst.EquipPartEnum.FRAGMENT then
            -- 奇异碎片
            if equipData["num"] == nil or equipData.num == 0 then
                if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Mythic, true,btn_unreplace) then
                    showUI(PanelNames.UIMythicDungonsPro)
                end
                return
            end
            weaponHandler.ReqFragmentInlay(this.currentPartnerId, equipData["itemId"])
        elseif equipData.heroType ~= this.curHeroType then
            -- TODO WG 职业不匹配
            UISysTips.AddMsg(getLanguage("EquipHeroType_NoMatch_Tips"));
            return
        else
            equipHandler.sendWear(this.currentPartnerId, equipData["itemId"])
        end

        -- AudioManager.Play(1049)
        --更换装备
        AudioManager.TryPlaySoundByWear(this.curHeroType,true)
        -- AudioManager.PlayInteractionVoice(this.heroId,0,AudioManager.InteractionTagTable[11].Tag)

        --this.onClickClose();
    end);

    local _equipIndex = 1
    if equipData["partnerId"] then
        _equipIndex = 0
        go:GetChild("hero"):GetChild("HeadIcon").url = equipData.heroIcon
    end
    go:GetController("equip").selectedIndex = _equipIndex

    btn_replace.onClick:Clear()
    btn_replace.onClick:Add( function()
        if this.curEquipData.part == EnumConst.EquipPartEnum.FRAGMENT then
            weaponHandler.ReqFragmentReplace(tostring(this.currentPartnerId),tostring(equipData["partnerId"]))
            return
        end
        if equipData.heroType ~= this.curHeroType then
            -- TODO WG 职业不匹配
            UISysTips.AddMsg(getLanguage("EquipHeroType_NoMatch_Tips"));
            return
        end
        --如果装备已有装备对象弹出提示
        if equipData["partnerId"] then
            if equipData["partnerId"] == this.currentPartnerId then
                --英雄已穿戴这件装备
                UISysTips.AddMsg("UIEquip_HeroHadWear")
                return
            end
            this.tipController.selectedIndex = 1;
            --是否要将 【%s】 装备的 【%s】 替换到 【%s】 身上？
            local _tipStr = getLanguage("UIEquip_IsReplaceEquip")
            _tipStr = string.format(_tipStr,equipData.heroName,equipData.name,this.curHeroName)
            this.tipText.text = _tipStr
            local ctrlItem = CtrlManager.GetCtrl(PanelNames.Item);
            if ctrlItem ~= nil then
                ctrlItem.initData(tipItem1, equipData);
                ctrlItem.initData(tipItem2, equipData);
            end
            if equipData["partnerId"] then
                this.tipIcon1.url = equipData.heroIcon
                this.tipIcon2.url = EnumConst.AtlasPath.ICONAtlas..curHeroData.icon
            end
            this.onClickSure(equipData.partnerId);
        else
            if this.curEquipData.part == EnumConst.EquipPartEnum.FRAGMENT then
                weaponHandler.ReqFragmentInlay(this.currentPartnerId, equipData["itemId"])
            else
                --直接穿装
                equipHandler.sendWear(this.currentPartnerId, equipData["itemId"]);
            end
            --更换装备
            AudioManager.TryPlaySoundByWear(this.curHeroType,true)
            AudioManager.PlayInteractionVoice(this.heroId,0,AudioManager.InteractionTagTable[11].Tag)
            --this.onClickClose();
        end
    end);

    table.insert(this.table_equipItem, go);

end

function this.onClickSure(otherPartnerId)
    this.btn_sure.onClick:Clear()
    this.btn_sure.onClick:Add( function()
        equipHandler.sendChange(this.currentPartnerId, this.curEquipData.part, otherPartnerId)
        --this.onClickClose();
        this.tipController.selectedIndex = 0;
    end)
end

function this.onClickCancel()
    this.tipController.selectedIndex = 0
end

function this.updateEquip()
    local _currentEquipment
    if this.curEquipData.part == EnumConst.EquipPartEnum.FRAGMENT then
        Util.PlayAction(this.fragmentEffectWrap, "idle1", false)
        _currentEquipment = StrangeFragmentManager.GetCurrentEquipFragment(this.currentPartnerId)
    else
        _currentEquipment = EquipManager.GetCurrentEquipment(this.currentPartnerId,this.curEquipData.part)
    end
    if _currentEquipment then
        this.curEquipData = _currentEquipment
        this.curEquipData.ctrollerIndex = 1
    end
    this.showCurEquipInfo();
    this.initEquipList();
end

function this.sortCondition(a, b)
    --装备战力  装备等级（可装备，从高到低  不可装备） 装备品质（从高到低）
    if a.power > b.power then
        return true;
    elseif a.power == b.power then
        return a.quality > b.quality
    end
    return false
end

return UIEquipList;

